package deep8jvmdvm;

import utils.PrintlnUtils;

import java.util.concurrent.locks.ReentrantLock;

/*
ReentrantLock 基本使用

ReentrantLock 的使用同 synchronized 有点不同，它的加锁和解锁操作都需要手动完成，如下所示：
 */

public class TestReentrantLock1 {
    ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) {
        TestReentrantLock1 testReentrantLock1 = new TestReentrantLock1();
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                testReentrantLock1.printLog();
            }
        });

        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                testReentrantLock1.printLog();
            }
        });
        thread1.start();
        thread2.start();
    }

    public void printLog() {
        try {
            lock.lock();
            for (int i = 0; i < 5; i++) {
                PrintlnUtils.println(Thread.currentThread().getName() + " is printing " + i);
            }
        } catch (Exception e) {

        } finally {
            lock.unlock();
        }
    }

    /*

    Thread-0 is printing 0

    Thread-0 is printing 1

    Thread-0 is printing 2

    Thread-0 is printing 3

    Thread-0 is printing 4

    Thread-1 is printing 0

    Thread-1 is printing 1

    Thread-1 is printing 2

    Thread-1 is printing 3

    Thread-1 is printing 4

    可以看出，使用 ReentrantLock 也能实现同 synchronized 相同的效果。

     */

}
